#!/bin/bash
#
# clandestine.googlecode.com
#

#$Cloverleaf daemon %CLOVERLEAF%

##Cloverleaf daemon listens to your laptop's special keys and do something
##  useful about it. Works only with Toshiba laptops, that are supported
##  by toshiba_acpi kernel module
##  (check if $KFNAME exists).
##
##  To see what codes are generated in your environment try --debug option.

#
# The options
#
readonly -a CLOVERLEAF=( 1 0 0 "extremely simple" )
readonly KFNAME="/proc/acpi/toshiba/keys"
readonly RFNAME=""
readonly SHKEY="hotkey"
readonly SREADY="hotkey_ready"
readonly SLEEPSECONDS="0.1"
#
# Clandestine lib
#
if ! source libclandestine.bash 2> /dev/null; then
	echo "Failed to include the Clandestine library, can't continue without it."
	exit 1
fi
#
# System functions
#
function KeyPressed () {
	local RESULT=$(awk -- "/^$SREADY:/ { print \$2 }" $KFNAME)
	(( ${RESULT//[^0-9]/} )) && return 0 # strip everything except the digits from the string
	return 1
}
function KeyRead () {
	awk -- "/^$SHKEY:/ { print \$2 }" $KFNAME
}
function KeyReset () {
	echo "$SREADY:0" > $KFNAME
}
function CleanExit () {
	Debug "Exit signal trapped, exiting clean."
	exit 0
}
#
# Key-mapped functions
#
function Key_0x0101 () {
	echo Fn-Esc Down!
}
#
# Main loop
#
trap CleanExit INT HUP KILL QUIT ABRT TERM STOP
[[ -w "$KFNAME" ]] || Fatal "$KFNAME is not writeable: check the file existance and your privileges."
while KeyPressed; do KeyReset; done # clear the buffer
while true; do
	while KeyPressed; do
		KEY=$(KeyRead)
		if $DEBUG; then
			Debug "$KEY"
		else
			FUNC="Key_$KEY"
			FunctionExists "$FUNC" && $FUNC
		fi
		KeyReset
	done
	sleep $SLEEPSECONDS
done
